/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.web.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.iwindplus.boot.domain.constant.CommonConstant.TraceConstant;
import com.iwindplus.boot.web.manager.context.ContextTransManager;
import jakarta.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

/**
 * RestTemplate拦截器.
 *
 * @author zengdegui
 * @since 2020/4/23
 */
@Slf4j
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {

    @Resource
    private ContextTransManager contextTransManager;

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        final Map<String, String> parameters = this.getStringMap(httpRequest);
        final Map<String, String> map = contextTransManager.buildRequestHeaderInMdc(parameters);
        if (MapUtil.isEmpty(map)) {
            return execution.execute(httpRequest, body);
        }
        HttpHeaders headers = httpRequest.getHeaders();
        map.entrySet().stream()
            .filter(entry -> ObjectUtil.isNotEmpty(entry.getValue()))
            .forEach(entry -> headers.set(entry.getKey(), entry.getValue()));
        return execution.execute(httpRequest, body);
    }

    private Map<String, String> getStringMap(HttpRequest httpRequest) {
        Map<String, String> parameters = new HashMap<>(16);
        final Map<String, String> map = httpRequest.getHeaders().toSingleValueMap();
        if (MapUtil.isEmpty(map)) {
            return parameters;
        }
        parameters.putAll(map);
        if (CharSequenceUtil.isNotBlank(parameters.get(TraceConstant.REAL_IP))) {
            return parameters;
        }
        parameters.put(TraceConstant.REAL_IP, httpRequest.getURI().getHost());
        return parameters;
    }
}